package com.udaos.modules.section.controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.udaos.common.base.Result;
import com.udaos.common.filter.PrivateFilter;
import com.udaos.common.page.DataTableColumn;
import com.udaos.common.page.DataTableOrder;
import com.udaos.models.region.Ud_region;
import com.udaos.models.resource.Ud_wx_resource;
import com.udaos.models.section.Ud_section_resource;
import com.udaos.models.section.Ud_wx_section;
import com.udaos.models.sys.Sys_user;
import com.udaos.modules.region.services.UdRegionService;
import com.udaos.modules.resource.services.UdWxResourceService;
import com.udaos.modules.section.services.UdSectionResourceService;
import com.udaos.modules.section.services.UdWxSectionService;
@IocBean
@At("/platform/section")
@Filters({ @By(type = PrivateFilter.class) })
public class UdWxSectionController {
	
	@Inject
	private UdWxSectionService sectionService;
	@Inject
	private UdRegionService regionService;
	@Inject
	private UdSectionResourceService sectionResourceService;
	@Inject
	private UdWxResourceService resourceService;
	/**
	 * 首页
	 */
	@At("")
	@Ok("beetl:/platform/section/index.html")
	@RequiresAuthentication
	public void index() {
		
	}
	
	/**
	 * 加载数据
	 * @param name
	 * @param length
	 * @param start
	 * @param draw
	 * @param order
	 * @param columns
	 * @return
	 */
	@At
	@Ok("json:full")
	@RequiresAuthentication
	public Object data(@Param("length") int length, @Param("start") int start, @Param("draw") int draw, @Param("::order") List<DataTableOrder> order, @Param("::columns") List<DataTableColumn> columns) {
		Cnd cnd = Cnd.NEW();
		cnd.and("delFlag", "=", "0");
		Subject subject = SecurityUtils.getSubject();
        Sys_user user = (Sys_user) subject.getPrincipal();
        cnd.and("company_id", "=", user.getUnit().getCompany_id());
		return sectionService.data(length, start, draw, order, columns, cnd, null);
	}
	/**
	 * 新增
	 * @return
	 */
	@At
	@Ok("beetl:/platform/section/add.html")
	@RequiresAuthentication
	public Object add() {
		Map<String,Object> map=new HashMap<String,Object>();
		//获取片区
		List<Ud_region> regions=sectionService.getRegions();
		map.put("regions", regions);
		return map;
	}
	/**
	 * do新增
	 * @param resource
	 * @param req
	 * @return
	 */
	@At
	@Ok("json")
	@RequiresAuthentication
	public Object addDo(@Param("..") Ud_wx_section section,@Param("resourceid") String resourceid,HttpServletRequest req) {
		try {
			Subject subject = SecurityUtils.getSubject();
			Sys_user user = (Sys_user) subject.getPrincipal();
			section.setCompany_id(user.getUnit().getCompany_id());
			section.setCreateBy(user.getId());
			section.setCreateAt((int)(System.currentTimeMillis()/1000));
			sectionService.insert(section);
			 //设置资源
            if(!Strings.isBlank(resourceid)){
            	String []resourceids=resourceid.split(",");
            	List<Ud_section_resource> crs=new ArrayList<Ud_section_resource>();
            	for (int i = 0; i < resourceids.length; i++) {
            		Ud_section_resource sr=new Ud_section_resource();
            		sr.setResource_id(resourceids[i]);
            		sr.setSection_id(section.getId());
            		crs.add(sr);
				}
            	sectionResourceService.insertList(crs);
            	
            }
			return Result.success("保存成功");
		} catch (Exception e) {
			System.err.println(e.getMessage());
			return Result.error("保存失败");
		}
	}
	/**
	 * 修改
	 * @param id
	 * @return
	 */
	@At("/edit/?")
	@Ok("beetl:/platform/section/edit.html")
	@RequiresAuthentication
	public Object edit(String id) {
		Map<String,Object> map=new HashMap<String,Object>();
		//获取片区
		List<Ud_region> regions=sectionService.getRegions();
		map.put("regions", regions);
		map.put("section", sectionService.fetch(id));
		List<Ud_section_resource> srs=sectionResourceService.query(Cnd.where("section_id", "=", id));
		String resourcesNames="";
		String resourcesids="";
		for(Ud_section_resource sr:srs){
			resourcesNames+=resourceService.fetch(sr.getResource_id()).getTitle()+",";
			resourcesids+=sr.getResource_id()+",";
		}
		if(!Strings.isBlank(resourcesids)){
			resourcesids=resourcesids.substring(0, resourcesids.length()-1);
		}
		if(!Strings.isBlank(resourcesNames)){
			resourcesNames=resourcesNames.substring(0, resourcesNames.length()-1);
		}
		map.put("resourcesNames", resourcesNames);
		map.put("resourcesids", resourcesids);
		return map;
	}
	
	/**
	 * do修改
	 * @param resource
	 * @param req
	 * @return
	 */
	@At
	@Ok("json")
	@RequiresAuthentication
	public Object editDo(@Param("..") Ud_wx_section section,@Param("resourceid") String resourceid,HttpServletRequest req) {
		try {
			sectionService.updateIgnoreNull(section);
			sectionResourceService.updateResource(section.getId(),resourceid);
			return Result.success("修改成功");
		} catch (Exception e) {
			return Result.error("修改失败");
		}
	}
	/**
	 * 删除
	 * @param id
	 * @param req
	 * @return
	 */
	@At("/delete/?")
    @Ok("json")
	@RequiresAuthentication
    public Object delete(String id, HttpServletRequest req) {
        try {
        	Ud_wx_section section = sectionService.fetch(id);
        	section.setDelFlag(true);
        	sectionService.updateIgnoreNull(section);
        	sectionResourceService.deleteBySectionId(id);
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
	
	
	/**
	 * 加载资源列表
	 * @param pid
	 * @return
	 */
	@At
	@Ok("json")
	@RequiresAuthentication
	public Object tree() {
		List<Map<String, Object>> tree = new ArrayList<>();
		
		List<Ud_wx_resource> resources=sectionService.findResources();
		for (Ud_wx_resource resource : resources) {
			 Map<String, Object> obj = new HashMap<>();
			obj.put("id", resource.getId());
			obj.put("text", resource.getTitle());				
			obj.put("children", false);
			tree.add(obj);
		}
		return tree;
	}
	
	/**
	 * 获取片区名称
	 * @param id
	 * @return
	 */
	@At
	@Ok("json")
	public String getRegionName(String id){
		if(!Strings.isBlank(id)){
			return regionService.fetch(id).getName();
		}
		return "";
	}
	

}
